home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9808 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: ghost.cbm.com!usenet
  2. From: Dave Payne <paynedc@cbm.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Determining the length of an int in string form
  5. Date: Wed, 13 Mar 1996 08:40:40 -0500
  6. Organization: CBM Technologies, INC
  7. Message-ID: <3146D058.DD7@cbm.com>
  8. NNTP-Posting-Host: cujo.cbm.com
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.0 (Win16; I)
  13.  
  14. Consider this:
  15.  
  16. I have a variable of type int, and I would like to use the sprintf() 
  17. function to write this variable to a string.  However, I want to 
  18. dynamically allocate the space for the string, and only malloc enough 
  19. space to hold the int.  Here's a code fragment that may illustrate this 
  20. more clearly:
  21.  
  22. void func1()  {
  23.  
  24.   int     i = 1234;
  25.   char     *a;
  26.  
  27.   /* 
  28.    * We need to malloc enough space to hold "The value of i is"
  29.    *  AND 1234.  The 4 + 1 is for the 4 bytes that 1234 will occupy
  30.    * in the string, and for a NULL terminator.
  31.    */
  32.   a = malloc(strlen("The value of i is ") + 4 + 1);
  33.   
  34.  /*
  35.    * Use sprintf() to build the desired string.
  36.    */                                                                    
  37.   
  38.   sprintf(a,"%s%d","The value of i is ",i);
  39.  
  40.   free(a);
  41.  
  42. }
  43.  
  44. In this example, I hardcoded the 4, because I knew that 1234 was 4 
  45. characters long.  I would like to be able to determine this at runtime, 
  46. and malloc enough space accordingly.  I guess what I need is a type of 
  47. itoa (similar to the atoi() C function) that will convert an integer to 
  48. its ASCII representation.  Then I could just do I strlen() on the return 
  49. value of itoa to figure out how many characters the integer will occupy 
  50. in string form.
  51.  
  52. Does anyone have any suggestions?
  53.  
  54. Much appreciated,
  55.     - Dave Payne
  56.       Atkins, VA
  57.